<template>
  <div class="portfolio-container">
    <!-- 头部 -->
    <div class="portfolio-header">
      <h1>我们的作品</h1>
      <p>用光影讲述故事，用镜头记录时代</p>
    </div>

    <div class="portfolio-content">
      <!-- 分类标签 -->
      <el-tabs v-model="activeTab" class="portfolio-tabs">
        <el-tab-pane label="全部作品" name="all"></el-tab-pane>
        <el-tab-pane label="电视剧" name="0"></el-tab-pane>
        <el-tab-pane label="电影" name="1"></el-tab-pane>
        <el-tab-pane label="综艺" name="6"></el-tab-pane>
      </el-tabs>

      <!-- 作品列表 -->
      <el-row :gutter="30">
        <el-col
            v-for="(item, index) in portfolioData"
            :key="item.id || index"
            :xs="24" :sm="12" :md="8" :lg="6"
        >
          <div class="portfolio-item" @click="handlePreview(item)">
            <div class="portfolio-image">
              <img :src="item.poster" :alt="item.title" />
              <div class="portfolio-overlay">
                <el-icon :size="40"><VideoPlay /></el-icon>
              </div>
            </div>
            <div class="portfolio-info">
              <h3>{{ item.title }}</h3>
              <div class="portfolio-meta">
                <span>{{ item.year }}</span>
                <el-tag
                    v-for="(tag, i) in item.workTagsArray || []"
                    :key="i"
                    :type="tagTypes[i % tagTypes.length]"
                    size="small"
                >
                  {{ tag }}
                </el-tag>
              </div>
              <p class="portfolio-desc">{{ truncateDescription(item.description) }}</p>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 分页 -->
      <div class="portfolio-pagination">
        <el-pagination
            background
            layout="prev, pager, next"
            :total="total"
            :page-size="pageSize"
            v-model:current-page="currentPage"
            @current-change="handlePageChange"
        />
      </div>
    </div>

    <!-- 作品预览对话框 -->
    <el-dialog
        v-model="previewVisible"
        :title="currentItem?.title"
        width="80%"
        :before-close="handleDialogBeforeClose"
        @closed="handleDialogClosed"
    >
      <div class="preview-content">
        <div class="preview-video">
          <video
              ref="videoPlayer"
              controls
              :poster="currentItem?.poster"
              style="width:100%"
              :key="videoKey"
          >
            <source :src="currentItem?.trailer" type="video/mp4">
            您的浏览器不支持 video 标签。
          </video>
        </div>
        <div class="preview-info">
          <h3>{{ currentItem?.title }}</h3>
          <p><strong>上映时间：</strong>{{ currentItem?.year }}</p>
          <p><strong>导演：</strong>{{ currentItem?.director }}</p>
          <p><strong>主演：</strong>{{ (currentItem?.actorsArray || []).join(' / ') }}</p>
          <p><strong>简介：</strong>{{ currentItem?.description }}</p>
          <div class="preview-tags">
            <el-tag
                v-for="(tag, i) in currentItem?.workTagsArray || []"
                :key="i"
                :type="tagTypes[i % tagTypes.length]"
            >
              {{ tag }}
            </el-tag>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="previewVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleContact">商务合作</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from 'vue'
import { VideoPlay } from '@element-plus/icons-vue'
import { getArtistsWorks } from '@/api/works'

const activeTab = ref('all')
const currentPage = ref(1)
const pageSize = ref(12) // 改成 ref，方便动态赋值
const total = ref(0)

const portfolioData = ref([])

const previewVisible = ref(false)
const currentItem = ref(null)
const videoPlayer = ref(null)
const videoKey = ref(0)

const tagTypes = ['', 'success', 'info', 'warning', 'danger']

// 判断设备类型并设置默认 pageSize
const setPageSizeByDevice = () => {
  if (window.innerWidth < 768) {
    pageSize.value = 3 // 移动端
  } else {
    pageSize.value = 4 // 电脑端
  }
}

// 获取作品数据
const fetchPortfolio = async () => {
  const params = {
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    type: activeTab.value !== 'all' ? activeTab.value : undefined
  }
  try {
    const res = await getArtistsWorks(params)
    portfolioData.value = (res.data.rows || []).map(item => ({
      ...item,
      actorsArray: item.actorsArray || (item.actors ? splitToArray(item.actors) : []),
      workTagsArray: item.workTagsArray || (item.workTags ? splitToArray(item.workTags) : [])
    }))
    total.value = res.data.total || 0
  } catch (err) {
    console.error('获取作品数据失败', err)
  }
}

// 中英文逗号分隔转数组
const splitToArray = (str) => {
  if (!str) return []
  return str.split(/[,，]/).map(s => s.trim()).filter(Boolean)
}

const truncateDescription = (text) => {
  if (!text) return ''
  return text.length > 50 ? text.substring(0, 50) + '...' : text
}

const handlePreview = async (item) => {
  currentItem.value = item
  previewVisible.value = true
  videoKey.value += 1
  await nextTick()
}

const handleDialogBeforeClose = (done) => {
  if (videoPlayer.value) {
    videoPlayer.value.pause()
  }
  done()
}

const handleDialogClosed = () => {
  if (videoPlayer.value) {
    videoPlayer.value.pause()
    videoPlayer.value.currentTime = 0
    videoPlayer.value.src = ''
    videoPlayer.value.load()
  }
}

const handlePageChange = (page) => {
  currentPage.value = page
  fetchPortfolio()
}

const handleContact = () => {
  previewVisible.value = false
}

// 监听 activeTab 变化，自动请求
watch(activeTab, () => {
  currentPage.value = 1
  fetchPortfolio()
})

watch(previewVisible, (newVal) => {
  if (!newVal && videoPlayer.value) {
    videoPlayer.value.pause()
  }
})

onMounted(() => {
  setPageSizeByDevice()
  fetchPortfolio()
  // 监听窗口变化，实时调整 pageSize
  window.addEventListener('resize', setPageSizeByDevice)
})
</script>



<style scoped>
/* 样式部分保持不变 */
.portfolio-container {
  padding: 80px 0;
  background-color: #f9f9f9;
}

.portfolio-header {
  text-align: center;
  margin-bottom: 60px;
}

.portfolio-header h1 {
  font-size: 36px;
  color: #333;
  margin-bottom: 20px;
}

.portfolio-header p {
  font-size: 18px;
  color: #666;
}

.portfolio-content {
  width: 90%;
  margin: 0 auto;
}

.portfolio-tabs {
  margin-bottom: 30px;
}

.portfolio-item {
  margin-bottom: 30px;
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  cursor: pointer;
}

.portfolio-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

.portfolio-image {
  position: relative;
  height: 0;
  padding-bottom: 140%;
  overflow: hidden;
}

.portfolio-image img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: all 0.3s ease;
}

.portfolio-item:hover .portfolio-image img {
  transform: scale(1.05);
}

.portfolio-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: all 0.3s ease;
}

.portfolio-item:hover .portfolio-overlay {
  opacity: 1;
}

.portfolio-overlay .el-icon {
  color: white;
}

.portfolio-info {
  padding: 20px;
}

.portfolio-info h3 {
  font-size: 18px;
  margin-bottom: 10px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.portfolio-meta {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  flex-wrap: wrap;
  gap: 8px;
}

.portfolio-meta span {
  font-size: 14px;
  color: #999;
  margin-right: 10px;
}

.portfolio-desc {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.portfolio-pagination {
  margin-top: 40px;
  text-align: center;
}

.preview-content {
  display: flex;
  gap: 30px;
}

.preview-video {
  flex: 1;
}

.preview-info {
  flex: 1;
}

.preview-info h3 {
  font-size: 24px;
  margin-bottom: 15px;
  color: #333;
}

.preview-info p {
  font-size: 16px;
  color: #555;
  margin-bottom: 10px;
  line-height: 1.6;
}

.preview-tags {
  margin-top: 15px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

@media (max-width: 768px) {
  .preview-content {
    flex-direction: column;
  }

  .portfolio-item {
    margin-bottom: 20px;
  }

  :deep(.el-dialog) {
    width: 90% !important;
    margin: 20px auto !important;
  }
}
</style>
